package island

import (
	"github.com/Unixeno/islands/volume"
	"github.com/opencontainers/runtime-spec/specs-go"
)

const (
	ReadPermission  uint8 = 1
	WritePermission uint8 = 2
)

type ContainerVolume struct {
	Destination string `json:"destination"`
	RW          uint8  `json:"rw"`
	Source      string `json:"source"`
	Name        string `json:"name"`
	Type        string `json:"type"`
}

func appendVolumeMount(spec *specs.Spec, m map[string]*ContainerVolume, id string) error {
	for _, v := range m {
		if v.Source == "" && v.Name == "" {
			mount, err := volume.Create(v.Name)
			if err != nil {
				return err
			}
			if err := mount.Register(id); err != nil {
				return err
			}
			v.Source = mount.MountPoint()
			v.Name = mount.Name
		} else if v.Source == "" {
			mount, err := volume.Open(v.Name)
			if err != nil {
				return err
			}
			if err := mount.Register(id); err != nil {
				return err
			}
			v.Source = mount.MountPoint()
		}

		if v.RW == 0 {
			v.RW = ReadPermission | WritePermission
		}
		var options []string
		if v.RW == 3 {
			options = []string{"rbind", "rw"}
		} else {
			options = []string{"rbind", "ro"}
		}
		spec.Mounts = append(spec.Mounts, specs.Mount{
			Destination: v.Destination,
			Type:        "none",
			Source:      v.Source,
			Options:     options,
		})
	}
	return nil
}
